package org.maverickjs.web.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.maverick.persistence.simple.jpa.ManagerFactory;

@WebFilter(urlPatterns={"/*"})
public class ManagerFilter implements Filter{
	
	public void init(FilterConfig evt) throws ServletException {
		
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		
		try {			
			EntityManager entityManager = ManagerFactory.currentManagerFactory().createEntityManager();
			request.setAttribute("default", entityManager);
			
			filterChain.doFilter(request, response);
			
			if (entityManager != null && entityManager.isOpen())
				entityManager.close();
			else{
				entityManager = (EntityManager)request.getAttribute("default");
				
				if (entityManager != null && entityManager.isOpen())
					entityManager.close();
			}	
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void destroy() {

	}

}
